package com.hz.web.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.hz.web.util.Constant;
import com.hz.web.util.Uid;

@Controller
@RequestMapping("upload")
public class UploadController {
	
	@ResponseBody
	@RequestMapping("/fileUpload")
	public void fileUpload(HttpServletRequest request,HttpServletResponse response,String fileObjectId,int MaxSize,String suffixStr,String savePath,int width,int height) throws IOException{
		MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;  
        MultipartFile file  =  multipartRequest.getFile(fileObjectId);//获取文件流
        String fileName = file.getOriginalFilename();//获取文件名
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());//获取文件后缀名
        String[] suffixs = suffixStr.split(",");
        boolean isSuffix = false;
        for(String str:suffixs){
        	if(str==suffix||str.equals(suffix)){
        		isSuffix=true;
        		break;
        	}
        }
        String result = "";
		String msg = "";
		String resultName = Uid.getUid()+"."+suffix;//UID新文件名
        if(isSuffix){
        	boolean isok =false;
        	if(MaxSize==0){
        		isok=true;
        	}
        	if(isok==true || file.getSize()/1024<=MaxSize){
        		
        		//String path = request.getSession().getServletContext().getRealPath("")+Constant.PATH.GETPATH(savePath);
                String path = "/usr/local/nginx/html" + Constant.PATH.GETPATH(savePath);
                System.out.println("图片上传路径UploadController, fileUpload, path==" + path);

                File targetFile = new File(path, resultName);
                if(!targetFile.exists()){ //文件夹是否存在
                    targetFile.mkdirs();  
                }  
                try {
                    file.transferTo(targetFile);
                    if(width!=0&&height!=0){
                        BufferedImage bufferedImg = ImageIO.read(targetFile);
                        if(bufferedImg.getWidth()!=width||bufferedImg.getHeight()!=height){
                        	
                        	if(targetFile.delete()){
                        		
                        	}
                        	result = "false";
                        	msg = Constant.MSG.IMG_WH+width+"*"+height;
                        }else{
                        	result="true";
                        }
                    }else{
                    	result = "true";
                    }
                } catch (Exception e) {  
                	msg = Constant.MSG.UNKNOW_ERROR;
                }  	
        	}else{
        		MaxSize=Integer.valueOf(MaxSize/1024);
        		msg = Constant.MSG.FILE_SIZE+MaxSize+"M";
        		result = "false";
        	}
        }else{
        	msg = Constant.MSG.FILE_TYPE;
        	result = "false";
        }
        response.setContentType("text/html; charset=UTF-8");  
        PrintWriter out;
        out = response.getWriter();
     
        String res = "{ success:'"+result+"', msg:'"+msg+"',imgurl:'" + resultName + "',oldname:'" + fileName + "'}";
        out.print(res);
        out.flush();
	}
	
	 /**
     * CKEditor 图片上传
     * Create of Elvis
     * @param request,HttpServletResponse response
     * @return JavaScript
	 * @throws IOException 
     */
	
    @RequestMapping(value = "/CKImgUpload",method=RequestMethod.POST)
    public void CKImgUpload(HttpServletRequest request,HttpServletResponse response) throws IOException {
    	response.setContentType("text/html; charset=UTF-8");  
    	String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");
    	
    	MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;  
        MultipartFile file  =  multipartRequest.getFile("upload");//获取文件流
        String fileName = file.getOriginalFilename();//获取文件名
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());//获取文件后缀名
        String resultName = Uid.getUid()+"."+suffix;//UID新文件名
        String strScript ="";
        if(Constant.FILE_TYPE.imgTypes().contains(suffix)){//验证文件格式
        	/*if(file.getSize()/1024<2048){*/
        	if(true){
        		//String path = request.getSession().getServletContext().getRealPath("")+Constant.PATH.CK_IMAGE_PATH1;
                String path = "/usr/local/nginx/html" + Constant.PATH.CK_IMAGE_PATH1;
                File targetFile = new File(path, resultName);
                if(!targetFile.exists()){ //文件夹是否存在
                    targetFile.mkdirs();  
                }  
                try {  
                    file.transferTo(targetFile);  
                	//String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ request.getContextPath() + "/";
                    String basePath = "http://zgaf.org:8080/";
                    strScript=Constant.MSG.getCKEditorMsg(CKEditorFuncNum,basePath+Constant.PATH.CK_IMAGE_PATH+"/"+resultName + "?timestamp=" + System.currentTimeMillis(),"");
                   
                } catch (Exception e) {  
                	strScript=Constant.MSG.getCKEditorMsg(CKEditorFuncNum,"",Constant.MSG.UNKNOW_ERROR);
                }  	
        	}/*else{
        		strScript=Constant.MSG.getCKEditorMsg(CKEditorFuncNum,"",Constant.MSG.IMG_SIZE_ERROR);
        	}*/
        }else{
        	strScript=Constant.MSG.getCKEditorMsg(CKEditorFuncNum,"",Constant.MSG.IMG_TYPE_ERROR);
        }
        
        PrintWriter out;
        out = response.getWriter();
        out.print(strScript);
        out.flush();
    }

}
